#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_LEN 128

/* 函数原型 */
int CheckLuhn ( const char * cardId, int sum[2] );
int ReadLine(char *s);

int main()
{
    int s[2]={0}, r;
    char id[MAX_LEN];

    while (ReadLine(id) > 0) {
        r = CheckLuhn(id, s);
        printf("%s,R=%d\t%d\t%d\n", id, r, s[0], s[1]);
    }
    return 0;
}

/* 字符串读取 */
int ReadLine(char *s)
{
    int n = 0, ch = 0;
    while((ch = getchar()) != '\n' && ch != EOF && n <= MAX_LEN - 1)
        s[n++] = ch;
    s[n]='\0';
    return n;
}

/* 字符串逆序 */
void strrev(char* p)
{
    char ch;
    char *q;

    int len = strlen(p);
    q = p + len - 1;

    while(p < q)
    {
        ch = *p;
        *p++ = *q;
        *q-- = ch;
    }
}

/* Luhn模10校验 */
int CheckLuhn( const char * cardId, int sum[2])
{
    int i, k;

    if(cardId == NULL) return 0;

    int len = strlen(cardId);

    /* 创建副本 */
    char *s = malloc((len + 1) * sizeof(char));
    strcpy(s, cardId);

    /* 逆序 */
    strrev(s);

    /* 累加器清0(非常重要) */
    sum[0] = sum[1] = 0;

    /* 奇数位 */
    for(i = 0; i < len; i += 2)
    {
        k = s[i] - '0';
        sum[0] += k;
    }

    /* 偶数位 */
    for(i = 1; i < len; i += 2)
    {
        k = (s[i] - '0') * 2;
        k = k >= 10 ? k - 9 : k;
        sum[1] += k;
    }

    /* 释放空间 */
    free(s);

    /* 校验并返回 */
    k = sum[0] + sum[1];

    if(k % 10 == 0)
    {
        return 0;
    }
    else
    {
        return 1;
    }
}
